package com.thinkgem.jeesite.modules.sys.security;

import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class MobileFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String url = httpRequest.getRequestURI();

        // 部分请求不需要登录权限
        if (url.contains("mobile/sys/area") || url.contains("mobile/toRegister") || url.contains("mobile/user/register") || url.contains("mobile/toProductDetail") || url.contains("mobile/toOrderDetailView")) {
            return true;
        }

        // 基于shiro校验是否登录
        Principal principal = UserUtils.getPrincipal();
        if (null == principal) {
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print("{\"code\":\"-2\",\"msg\":\"未登录\",\"timestamp\":\"" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "\"}");
            return false;
        } catch (IOException e) {
            return false;
        }
    }

}
